package com.marisfrolg.storage;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnLongClick;
import com.marisfrolg.base.BaseApplication;
import com.marisfrolg.entity.PrepareBin;
import com.marisfrolg.entity.PrepareProduct;
import com.marisfrolg.entity.json.JsonBinStock;
import com.marisfrolg.entity.json.JsonBinStockItem;
import com.marisfrolg.entity.json.JsonMoveResult;
import com.marisfrolg.entity.json.MoveResultMessage;
import com.marisfrolg.entity.json.User;
import com.marisfrolg.util.ReadCodeController;
import com.marisfrolg.util.StringUtil;
import com.marisfrolg.util.WebServicesUtil;

public class MoveActivity extends ItemActivity {
	private LayoutInflater inflater;
	private PopupWindow popWindow;
	private PopupWindow resultWindow;
	@ViewInject(R.id.triggerBt)
	private com.beardedhen.androidbootstrap.BootstrapButton triggerBt;
	@ViewInject(R.id.showresult)
	private com.beardedhen.androidbootstrap.BootstrapButton showresult;
	@ViewInject(R.id.cangweihao)
	private com.beardedhen.androidbootstrap.BootstrapEditText cangweihao;
	@ViewInject(R.id.cangweihaosingle)
	private com.beardedhen.androidbootstrap.BootstrapEditText cangweihaosingle;
	@ViewInject(R.id.srccangweihao)
	private com.beardedhen.androidbootstrap.BootstrapEditText srccangweihao;
	private BootstrapButton srcconfirm;
	@ViewInject(R.id.kuanhaoList)
	private LinearLayout kuanhaoList;
	@ViewInject(R.id.kuanhaoshu)
	private TextView kuanhaoshu;
	@ViewInject(R.id.zongshu)
	private TextView zongshu;
	@ViewInject(R.id.cangweireached)
	private TextView cangweireached;
	@ViewInject(R.id.cleanicon)
	private View cleanicon;
	@ViewInject(R.id.inputproduct)
	private com.beardedhen.androidbootstrap.BootstrapEditText inputproduct;
	private LinearLayout cangweiList;
	private BootstrapButton addcangweihao;
	private BootstrapButton cleancangweihao;
	private AlertDialog alert;
	private static final String TARGETBINNO= "TARGETBINNO";
	private static final int CLEANNUM=-4444;
	private SharedPreferences sp;
	
	private ReadCodeController rcc;
	private WSHandler wHandler;
	private WebServicesUtil ws;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_move);
		inflater=LayoutInflater.from(this);
		ViewUtils.inject(this);
		sHandler=new ScanHandler(this);
		wHandler=new WSHandler(this);
		ws=new WebServicesUtil(this,wHandler);
		rcc=((BaseApplication)getApplication()).getReadCodeController();
		rcc.setHandler(sHandler);
		rcc.Open();
		initPopWindow();
		srcconfirm=(BootstrapButton)findViewById(R.id.srcconfirm);
		refresh();
		//批量移动功能取消
		triggerBt.setVisibility(View.GONE);
		//是否已经选中目的和源仓位
		sp = getSharedPreferences("MOVEINFO", MODE_PRIVATE);
		String tarbinno=sp.getString(TARGETBINNO, "");
		JsonBinStock jbs;
		try {
			jbs = db.findFirst(JsonBinStock.class);
			if(jbs!=null&&(!"".equals(jbs.getSOURCEBIN()))){
				srccangweihao.setText(jbs.getSOURCEBIN());
			}
			initResultWindow();
		} catch (DbException e) {
			e.printStackTrace();
		}
		if(!"".equals(tarbinno)){
			cangweihao.setText(tarbinno);//失效
			cangweihaosingle.setText(tarbinno);
		}
	}
	//清除已扫描款号信息
	@OnLongClick(R.id.cleanicon)
	public void cleanProduct(View v){
		new AlertDialog.Builder(MoveActivity.this).setTitle("提示").setMessage("确定删除已扫款号信息吗?").setPositiveButton("确定",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					List<JsonBinStockItem> jlist=db.findAll(JsonBinStockItem.class);
					if(jlist==null||jlist.size()==0){
						return;
					}
					for (JsonBinStockItem jsonBinStockItem : jlist) {
						jsonBinStockItem.setUQUAN(0);
					}
					db.updateAll(jlist, "uquan");
				} catch (DbException e) {
					e.printStackTrace();
				}
				refresh();
			}
		}).setNegativeButton("取消", null).show();
	}
	//清除所有信息
	@OnClick(R.id.cleanicon)
	public void cleanAll(View v){
		new AlertDialog.Builder(MoveActivity.this).setTitle("提示").setMessage("确定该页面的所有信息吗?").setPositiveButton("确定",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					db.deleteAll(PrepareBin.class);
					db.deleteAll(PrepareProduct.class);
					db.deleteAll(JsonBinStock.class);
					db.deleteAll(JsonBinStockItem.class);
					Editor editor = sp.edit();
					editor.putString(TARGETBINNO,"");
					editor.commit();
					Intent in=new Intent(MoveActivity.this,MoveActivity.class);
					startActivity(in);
					finish();
				} catch (DbException e) {
					e.printStackTrace();
				}
				finish();
			}
		}).setNegativeButton("取消", null).show();
	}
	//点击仓位号提供目标仓位号选择
	@OnClick(R.id.cangweihao)
	public void chooseCangwei(View v){
		triggerBt.performClick();
	}
	//点击仓位号提供目标仓位号选择
	@OnClick(R.id.cangweihaosingle)
	public void chooseCangweiSingle(View v){
		final EditText et=new EditText(this);
		new AlertDialog.Builder(this).setView(et).setPositiveButton("确定",new DialogInterface.OnClickListener(){
			public void onClick(DialogInterface dialog, int which) {
				String value=(et.getText()+"").trim().toUpperCase(Locale.US);
				cangweihaosingle.setText(value);
				Editor editor = sp.edit();
				editor.putString(TARGETBINNO,value);
				editor.commit();
				play_sound(true);
			}
		}).setNegativeButton("取消", null).setTitle("提示").setMessage("输入目的仓位号:").show();
	}
	
	//将目标仓位号信息清空
	@OnLongClick(R.id.cangweihaotitle)
	public void cleancangwei(View v){
		cangweihao.setText("");
		Editor editor = sp.edit();
		editor.putString(TARGETBINNO,"");
		editor.commit();
		play_sound(true);
	}
	//将目标仓位号信息清空
	@OnLongClick(R.id.cangweihaotitlesingle)
	public void cangweihaotitlesingle(View v){
		cangweihaosingle.setText("");
		Editor editor = sp.edit();
		editor.putString(TARGETBINNO,"");
		editor.commit();
		play_sound(true);
	}
	//将源仓位号信息清空
	@OnLongClick(R.id.srccangweihaotitle)
	public void cleansrccangwei(View v){
		srccangweihao.setText("");
		play_sound(true);
	}
	//拉取源仓位信息
	@OnClick(R.id.srcconfirm)
	public void chooseSrcCangwei(View v){
		String s=srccangweihao.getText()+"";
		s=s.toUpperCase(Locale.US).trim();
		srccangweihao.setText(s);
		if(StringUtil.isEmpty(s)){
			Toast.makeText(this, "请输入源仓位", Toast.LENGTH_SHORT).show();
			play_sound(false);
		}
		HashMap<String, Object>params=new HashMap<String, Object>();
		Gson gson=new Gson();
		Type type = new TypeToken<User>() {}.getType();
		params.put("USER", gson.toJson(loginUser, type));
		params.put("BINNO", s);
		progressDialog = ProgressDialog.show(MoveActivity.this, "查询中", "请稍候...", true, true);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				WebServicesUtil.setConnectionTimeOut();
			}
		});
		ws.call(WebServicesUtil.ACTION_MoveBINSTOCK, params, WebServicesUtil.URL_ACTION_MoveBINSTOCK, WebServicesUtil.METHOD_ACTION_MoveBINSTOCK);
	}
	
	//添加一个产品
	@OnClick(R.id.productconfirm)
	public void addProduct(View v){
		String productno=(inputproduct.getText()+"").toUpperCase(Locale.US).trim();
		srccangweihao.setText(cangweireached.getText()+"");
		Message msg=new Message();
		msg.what=ReadCodeController.CODEREAD;
		msg.obj=productno;
		sHandler.dispatchMessage(msg);
	}
	//添加一个产品
	@OnLongClick(R.id.productconfirm)
	public void editProductNum(View v){
		final String productno=(inputproduct.getText()+"").toUpperCase(Locale.US).trim();
		srccangweihao.setText(cangweireached.getText()+"");
		final EditText et=new EditText(this);
		new AlertDialog.Builder(this).setTitle("修改款号:"+productno+" 的数量").setView(et).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try{
					int value=Integer.valueOf((et.getText()+"").trim());
					if(value==0){
						value=CLEANNUM;
					}
					if(value>0||value==CLEANNUM){
						Message msg=new Message();
						msg.what=ReadCodeController.CODEREAD;
						msg.obj=productno;
						msg.arg1=value;
						sHandler.dispatchMessage(msg);
					}
				}catch (Exception e){
					e.printStackTrace();
					Toast.makeText(MoveActivity.this, "请输入数字", Toast.LENGTH_LONG).show();
				}
			}
		}).setNegativeButton("取消", null).show();
	}
	
	@OnClick(R.id.submit)
	public void submitMove(View v){
		new AlertDialog.Builder(this).setTitle("提示").setMessage("是否提交当前操作").setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				HashMap<String, Object>params=new HashMap<String, Object>();
				Gson gson=new Gson();
				Type type = new TypeToken<User>() {}.getType();
				params.put("USER", gson.toJson(loginUser, type));
				JsonBinStock jsonBinStock=null;
				try {
					jsonBinStock=db.findFirst(JsonBinStock.class);
					List<JsonBinStockItem> jsonBinStockItems=db.findAll(Selector.from(JsonBinStockItem.class).orderBy("cat", true));
//					jsonBinStock.setDESTBIN((""+cangweihao.getText()).toUpperCase(Locale.US).trim());
					jsonBinStock.setDESTBIN((""+cangweihaosingle.getText()).toUpperCase(Locale.US).trim());
					jsonBinStock.setIV_LGNUM(loginUser.getWorklgnum());
					jsonBinStock.setITEMS(jsonBinStockItems);
					String json=gson.toJson(jsonBinStock, JsonBinStock.class);
					params.put("MOVEIN",json);
				} catch (DbException e1) {
					e1.printStackTrace();
				}finally{
					if(jsonBinStock==null||jsonBinStock.notFinish()){
						play_sound(false);
						Toast.makeText(MoveActivity.this, "信息未完成", Toast.LENGTH_LONG).show();
						return;
					}
				}
				if(progressDialog!=null){
					progressDialog.cancel();
					progressDialog.dismiss();
					progressDialog=null;
				}
				progressDialog = ProgressDialog.show(MoveActivity.this, "提交中", "请稍候...", true, true);
				progressDialog.setCanceledOnTouchOutside(false);
				progressDialog.setOnCancelListener(new OnCancelListener() {
					public void onCancel(DialogInterface dialog) {
						WebServicesUtil.setConnectionTimeOut();
					}
				});
				ws.call(WebServicesUtil.ACTION_MoveBIN, params, WebServicesUtil.URL_ACTION_MoveBIN, WebServicesUtil.METHOD_ACTION_MoveBIN);
			}
		}).setNegativeButton("取消", null).show();
		
	}
	
	
	//初始化仓位选择弹出窗口
	@SuppressWarnings("deprecation")
	private void initPopWindow() {
		final View vPopupWindow=inflater.inflate(R.layout.move_pop_window, null, false);
		triggerBt.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(popWindow.isShowing()){
					popWindow.dismiss();
				}else{
					popWindow.showAsDropDown(triggerBt, 100, 10);
				}
			}
		});
		popWindow = new PopupWindow(vPopupWindow, 600, 600,true);
		popWindow.setOutsideTouchable(true);
		popWindow.setFocusable(true);
		popWindow.setBackgroundDrawable(new BitmapDrawable());
		cangweiList=(LinearLayout)vPopupWindow.findViewById(R.id.cangweiList);
		cleancangweihao=(BootstrapButton)vPopupWindow.findViewById(R.id.cleancangweihao);
		cleancangweihao.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				new AlertDialog.Builder(MoveActivity.this).setTitle("提示").setMessage("确定清空所有已扫仓位?").setPositiveButton("确定",new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						try {
							db.deleteAll(PrepareBin.class);
							refreshWindow();
						} catch (DbException e) {
							e.printStackTrace();
						}
					}
				}).setNegativeButton("取消", null).show();
			}
		});
		addcangweihao=(BootstrapButton)vPopupWindow.findViewById(R.id.addcangweihao);
		addcangweihao.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				final EditText binno=new EditText(MoveActivity.this);
				LayoutParams lp=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
				binno.setLayoutParams(lp);
				alert=new AlertDialog.Builder(MoveActivity.this).setView(binno).setTitle("添加仓位号...").setMessage("输入仓位号:(直接扫描可添加)").setPositiveButton("确定",new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Message msg=new Message();
						msg.what=ReadCodeController.CODEREAD;
						msg.obj=(binno.getText()+"").toUpperCase(Locale.US).trim();
						sHandler.dispatchMessage(msg);
						refreshWindow();
					}
				}).setNegativeButton("取消", null).create();
				alert.setOnKeyListener(new DialogInterface.OnKeyListener() {
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						if(event.getAction()==KeyEvent.ACTION_DOWN&&(keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10|| keyCode == KeyEvent.KEYCODE_F11||keyCode == KeyEvent.KEYCODE_BACK)){
							rcc.scan_start();
						}else if(event.getAction()==KeyEvent.ACTION_UP&&(keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10|| keyCode == KeyEvent.KEYCODE_F11)){
							rcc.scan_stop();
						}
						return false;
					}
				});
				alert.setCancelable(false);
				alert.show();
			}
		});
		refreshWindow();
	}
	@OnLongClick(R.id.showresult)
	public void delResult(View v){
		new AlertDialog.Builder(MoveActivity.this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					db.deleteAll(JsonMoveResult.class);
					db.deleteAll(MoveResultMessage.class);
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
		}).setTitle("提示").setMessage("删除结果集?").show();
	}
	
	@SuppressWarnings("deprecation")
	private void initResultWindow() throws DbException{
		final View vPopupWindow=inflater.inflate(R.layout.move_popresult_window, null, false);
		resultWindow = new PopupWindow(vPopupWindow,500,700,true);
		resultWindow.setOutsideTouchable(true);
		resultWindow.setFocusable(true);
		resultWindow.setBackgroundDrawable(new BitmapDrawable());
		showresult.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(resultWindow.isShowing()){
					resultWindow.dismiss();
				}else{
					resultWindow.showAsDropDown(showresult);
				}
			}
		});
		TextView title=(TextView) vPopupWindow.findViewById(R.id.title);
		JsonMoveResult jmr=db.findFirst(JsonMoveResult.class);
		if(jmr==null){
			return;
		}
//		title.setText(cangweireached.getText()+" \n=> "+cangweihao.getText()+" || "+jmr.EV_SEVERITY);
		title.setText(cangweireached.getText()+" \n=> "+cangweihaosingle.getText()+" || "+jmr.EV_SEVERITY);
		LinearLayout resultList=(LinearLayout)vPopupWindow.findViewById(R.id.resultList);
		List<MoveResultMessage> msgs=db.findAll(Selector.from(MoveResultMessage.class).orderBy("id"));
		if(msgs==null||msgs.size()==0){
			return;
		}
		boolean hasError=jmr.EV_SEVERITY.contains("E");
		for (MoveResultMessage tohuOutMessage : msgs) {
			View msgview = inflater.inflate(R.layout.pickout_pop_item, null);
			TextView msgid=(TextView)msgview.findViewById(R.id.msgid);
			msgid.setText(""+tohuOutMessage.getID());
			TextView msgnum=(TextView)msgview.findViewById(R.id.msgnum);
			msgnum.setText(""+tohuOutMessage.getNUMBER());
			TextView msgtext=(TextView)msgview.findViewById(R.id.msgtext);
			msgtext.setText(""+tohuOutMessage.getMESSAGE());
			TextView msgtype=(TextView)msgview.findViewById(R.id.msgtype);
			msgtype.setText(""+tohuOutMessage.getTYPE());
			tohuOutMessage.getID();
			if(tohuOutMessage.getTYPE().contains("E")){//失败
				msgview.setBackgroundResource(R.drawable.item_bg_red);
				hasError=true;
			}else if(tohuOutMessage.getTYPE().contains("S")){//成功
				msgview.setBackgroundResource(R.drawable.item_bg_green);
			}else{//其他
				continue;
//				msgview.setBackgroundResource(R.drawable.item_bg_blue);
			}
			resultList.addView(msgview);
			LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) msgview.getLayoutParams();
			lp.topMargin = 10;
		}
		if(hasError){
			showresult.setBootstrapType("danger");
			play_sound(false);
			new AlertDialog.Builder(MoveActivity.this).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					if(resultWindow.isShowing()){
//						resultWindow.dismiss();
					}else{
						resultWindow.showAsDropDown(showresult);
					}
				}
			}).setTitle("提示").setMessage("提交结果中有错误").show();
		}
	}
	//更新款号数据
	private void refresh(){
		try {
			kuanhaoList.removeAllViews();
			JsonBinStock jbs=db.findFirst(JsonBinStock.class);
			if(jbs!=null&&jbs.getSOURCEBIN()!=null&&(!"".equals(jbs.getSOURCEBIN()))){
				cangweireached.setText(Html.fromHtml("<u>"+jbs.getSOURCEBIN()+"</u>"));
			}
			List<JsonBinStockItem> jsonBinStockItems=db.findAll(Selector.from(JsonBinStockItem.class).orderBy("matnr,cat",false));
			if(jsonBinStockItems==null||jsonBinStockItems.size()==0){
				return;
			}
			OnClickListener o=new OnClickListener() {
				public void onClick(View v) {
					final RelativeLayout p=(RelativeLayout)(v.getParent()); 
					TextView productno=(TextView)p.findViewById(R.id.productno);
					TextView seq=(TextView)p.findViewById(R.id.seq);
					new AlertDialog.Builder(MoveActivity.this).setTitle("提示").setMessage("#"+seq.getText()+"-确定减少1个款号为:"+productno.getText()).setPositiveButton("确定",new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							TextView idtv=(TextView)p.findViewById(R.id.id);
							int id=Integer.valueOf(idtv.getText().toString().trim());
							try {
								// 
								JsonBinStockItem pp=db.findById(JsonBinStockItem.class, id);
								if(pp!=null){
									if(pp.UQUAN>0){
										pp.UQUAN-=1;
										db.update(pp, "uquan");
										MoveActivity.this.play_sound(true);
									}else{
										Toast.makeText(MoveActivity.this, "数量已经为零", Toast.LENGTH_LONG).show();;
									}
								}
							} catch (DbException e) {
								e.printStackTrace();
							}
							refresh();
						}
					}).setNegativeButton("取消", null).show();
				}
			};
			int i=0;
			int sum=0;
			for (JsonBinStockItem jsonBinStockItem : jsonBinStockItems) {
				if(jsonBinStockItem.getQUAN()==0){
					continue;
				}
				i++;
				View cangweiItem = inflater.inflate(R.layout.move_item, null);
				TextView bb=(TextView)cangweiItem.findViewById(R.id.seq);
				bb.setText((i<10?"0":"")+i);
				TextView productno=(TextView)cangweiItem.findViewById(R.id.productno);
				productno.setText(jsonBinStockItem.getMATNR());
				TextView id=(TextView)cangweiItem.findViewById(R.id.id);
				id.setText(""+jsonBinStockItem.getId());
				View reduce=cangweiItem.findViewById(R.id.reduce);
				reduce.setOnClickListener(o);
				TextView quantity=(TextView)cangweiItem.findViewById(R.id.quantity);
				sum+=jsonBinStockItem.UQUAN;
				View line=cangweiItem.findViewById(R.id.disableline);
				if((jsonBinStockItem.getXFELD()+"").contains("X")){
					line.setVisibility(View.VISIBLE);
				}
				SpannableStringBuilder style=new SpannableStringBuilder(""+jsonBinStockItem.UQUAN+"/"+jsonBinStockItem.QUAN);
				int end=(jsonBinStockItem.UQUAN+"").length();
				if(jsonBinStockItem.UQUAN==jsonBinStockItem.QUAN){
					style.setSpan(new ForegroundColorSpan(Color.GREEN),0,end,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				}else{
					style.setSpan(new ForegroundColorSpan(Color.RED),0,end,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
				}
				
				quantity.setText(style);
				kuanhaoList.addView(cangweiItem);
				LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) cangweiItem.getLayoutParams();
				lp.topMargin = 10;
			}
			kuanhaoshu.setText(""+i);
			zongshu.setText(""+sum);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//更新预置仓位号
	private void refreshWindow(){
		try {
			cangweiList.removeAllViews();
			List<PrepareBin> prepareBins=db.findAll(Selector.from(PrepareBin.class).orderBy("date", false));
			if(prepareBins==null||prepareBins.size()==0){
				return;
			}
			//选择仓位按键,和删除按键公用监听
			OnClickListener o=new OnClickListener() {
				public void onClick(View v) {
					final RelativeLayout p=(RelativeLayout)(v.getParent()); 
					if(v.getId()==R.id.choose){
						TextView binno=(TextView)p.findViewById(R.id.binno);
						cangweihao.setText(binno.getText());
						Editor editor = sp.edit();
						editor.putString(TARGETBINNO, binno.getText()+"");
						editor.commit();
						if(popWindow!=null){
							popWindow.dismiss();
						}
					}else if(v.getId()==R.id.reduce){
						TextView binno=(TextView)p.findViewById(R.id.binno);
						new AlertDialog.Builder(MoveActivity.this).setTitle("提示").setMessage("确定删除仓位:"+binno.getText()).setPositiveButton("确定",new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								TextView idtv=(TextView)p.findViewById(R.id.id);
								int id=Integer.valueOf(idtv.getText().toString().trim());
								try {
									db.deleteById(PrepareBin.class, id);
								} catch (DbException e) {
									e.printStackTrace();
								}
								refreshWindow();
							}
						}).setNegativeButton("取消", null).show();
					}
				}
			};
			//根据数据产生UI
			int i=0;
			for (PrepareBin prepareBin : prepareBins) {
				i++;
				View cangweiItem = inflater.inflate(R.layout.move_pop_item, null);
				BootstrapButton bb=(BootstrapButton)cangweiItem.findViewById(R.id.choose);
				bb.setText((i<10?"#0":"#")+i);
				TextView binno=(TextView)cangweiItem.findViewById(R.id.binno);
				binno.setText(prepareBin.getBinno());
				TextView id=(TextView)cangweiItem.findViewById(R.id.id);
				id.setText(""+prepareBin.getId());
				View reduce=cangweiItem.findViewById(R.id.reduce);
				reduce.setOnClickListener(o);
				bb.setOnClickListener(o);
				if(prepareBin.isIsused()){
					TextView isused=(TextView)cangweiItem.findViewById(R.id.isused);
					isused.setText("已使用");
				}
				cangweiList.addView(cangweiItem);
			}
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	
	
	private static class ScanHandler extends Handler {
		WeakReference<MoveActivity> wactivity;
		ScanHandler(MoveActivity activity) {
			wactivity = new WeakReference<MoveActivity>(activity);
		}
		public void handleMessage(Message msg) {
			MoveActivity activity = wactivity.get();
			switch (msg.what) {
			case ReadCodeController.CODEREAD:{
				if(("".equals(activity.srccangweihao.getText()+""))&&(activity.popWindow == null || !activity.popWindow.isShowing())){//没有pop窗口时 也没有 源仓位
					if(StringUtil.isEmpty(msg.obj+"")){
						activity.play_sound(false);
					}
					activity.srccangweihao.setText(""+msg.obj);
					activity.srcconfirm.performClick();
				}else if (activity.popWindow == null || !activity.popWindow.isShowing()) {//没有pop窗口时---拿货，目的仓位
					if((msg.obj+"").length()<10){//扫入的是仓位号
						activity.cangweihaosingle.setText(msg.obj+"");
						Editor editor = activity.sp.edit();
						editor.putString(TARGETBINNO, msg.obj+"");
						editor.commit();
					}else{//扫入的是产品
						try {
							activity.inputproduct.setText(""+msg.obj);
//							PrepareProduct pp=activity.db.findFirst(Selector.from(PrepareProduct.class).where(WhereBuilder.b("productno", "=", msg.obj+"")));
							List<JsonBinStockItem> jlist=activity.db.findAll(Selector.from(JsonBinStockItem.class).where(WhereBuilder.b("matnr","=",msg.obj+"")).orderBy("cat"));
							JsonBinStockItem jsbi=null;
							for (JsonBinStockItem jsonBinStockItem : jlist) {
								if(jsonBinStockItem.UQUAN<jsonBinStockItem.QUAN&&(!jsonBinStockItem.getXFELD().contains("X"))){
									jsbi=jsonBinStockItem;
									break;
								}
							}
							if(jsbi==null){
								activity.play_sound(false);
								if(jlist.size()>0){
									Toast.makeText(activity, "超出库存", Toast.LENGTH_LONG).show();
								}else{
									Toast.makeText(activity, "没有库存", Toast.LENGTH_LONG).show();
								}
								
								return;
							}
							if(jsbi.getUQUAN()<jsbi.getQUAN()){
								if(msg.arg1!=0){
									if(msg.arg1>jsbi.getQUAN()){
										jsbi.setUQUAN(jsbi.getUQUAN());
									}else if(msg.arg1<0){
										jsbi.setUQUAN(0);
									}else{
										jsbi.setUQUAN(msg.arg1);
									}
								}else{
									jsbi.setUQUAN(jsbi.getUQUAN()+1);
								}
								activity.db.update(jsbi, "uquan");
							}
							activity.refresh();
						} catch (DbException e) {
							e.printStackTrace();
						}
					}
				} else {
					if(StringUtil.isEmpty(msg.obj+"")){
						new AlertDialog.Builder(activity).setTitle("提示").setMessage("不可为空").setPositiveButton("确定",null).show();
						activity.play_sound(false);
						return;
					}
					try {
						PrepareBin pb=activity.db.findFirst(Selector.from(PrepareBin.class).where(WhereBuilder.b("binno", "=", msg.obj+"")));
						if(pb!=null){
							new AlertDialog.Builder(activity).setPositiveButton("确定",null).setTitle("提示").setMessage("已存在").show();
							activity.play_sound(false);
							return;
						}
						PrepareBin pbb=new PrepareBin();
						pbb.setBinno((msg.obj+"").trim().toUpperCase(new Locale("US")));
						pbb.date=new Date(System.currentTimeMillis());
						pbb.setIsused(false);
						activity.db.saveBindingId(pbb);
						activity.refreshWindow();
					} catch (DbException e) {
						e.printStackTrace();
					}
				}
				activity.play_sound(true);
				break;
			}
			default:
				break;
			}
		}
	};
	
	
	@Override
	public void onBackPressed() {
		if(popWindow.isShowing()){
			popWindow.dismiss();
			return;
		}
		super.onBackPressed();
	}
	public void play_sound(boolean success) {
		try {
			if(success){
				mediaPlayer = MediaPlayer.create(this, R.raw.success);
			}else{
				mediaPlayer = MediaPlayer.create(this, R.raw.error);
			}
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static class WSHandler extends Handler {
		WeakReference<MoveActivity> wactivity;
		WSHandler(MoveActivity activity) {
			wactivity = new WeakReference<MoveActivity>(activity);
		}

		public void handleMessage(Message msg) {
			MoveActivity activity = wactivity.get();
			switch (msg.what) {
			case WebServicesUtil.ACTION_MoveBINSTOCK:{
				if((msg.obj+"").startsWith("错误")){
					activity.play_sound(false);
					Toast.makeText(activity, msg.obj+"", Toast.LENGTH_LONG).show();
					break;
				}
				activity.jsonToDb(msg.obj+"");
				activity.refresh();
				activity.play_sound(true);
				break;
			}
			case WebServicesUtil.ACTION_MoveBIN:{
				if((msg.obj+"").startsWith("错误")){
					activity.play_sound(false);
					Toast.makeText(activity, msg.obj+"", Toast.LENGTH_LONG).show();
					break;
				}
				Gson gson=new Gson();
				Type type = new TypeToken<JsonMoveResult>() {}.getType();
				JsonMoveResult jmr=gson.fromJson(msg.obj+"", type);
				try {
					activity.db.deleteAll(JsonMoveResult.class);
					activity.db.deleteAll(MoveResultMessage.class);
					activity.db.saveBindingId(jmr);
					activity.db.saveAll(jmr.getET_BAPIRET());
					activity.initResultWindow();
					activity.srccangweihao.setText(activity.cangweireached.getText()+"");
					activity.srcconfirm.performClick();
					activity.showresult.performClick();
				} catch (DbException e) {
					e.printStackTrace();
				}
				
				break;
			}
			case WebServicesUtil.NETUNREACHABLE:{
				Toast.makeText(activity, "网络无法连接或连接已取消,请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
			case WebServicesUtil.TIMEOUT:{
				new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("提示").setMessage("连接超时").show();
				break;
			}
			default:
				break;
			}
			if(activity.progressDialog!=null&&activity.progressDialog.isShowing()){
				activity.progressDialog.dismiss();
			}
		}
	}


	public void jsonToDb(String msg) {
		JsonBinStock jsb=new JsonBinStock();
		Gson gson = new Gson();
		Type type = new TypeToken<List<JsonBinStockItem>>() {}.getType();
		List<JsonBinStockItem> jlist=gson.fromJson(msg, type);
		jsb.setITEMS(jlist);
		jsb.setSOURCEBIN(srccangweihao.getText()+"");
		try {
			if(jlist!=null&&jlist.size()>0){
				db.deleteAll(JsonBinStock.class);
				db.deleteAll(JsonBinStockItem.class);
			}
			db.saveBindingId(jsb);
			db.saveAll(jlist);
		} catch (DbException e) {
			e.printStackTrace();
		}
	};
}
